"""tool"""
from flask import Blueprint, request, g
from psycopg2 import extras
import orjson
import httpx
from util.response import response
from util import (handle_auth, appointment_records, visitor_sign_out_func,
                  handle_room, signout_handle_room,
                  hi_kisapi_proxy_func, appointment_cancel,
                  cabinet_status, inspect_cabinet_status)

tool_api = Blueprint('tool_api', __name__)


@tool_api.route("/api/tool/delete_face_information_without_cabinet", methods=['GET'])
def delete_face_information_without_cabinet():
    """删除没有柜子的人脸信息"""
    max_results = 20
    i = 0
    employee = []
    while True:
        search_result_position = i * max_results
        params = {
            "UserInfoSearchCond": {
                "searchID": "db51c04d-025a-45b3-895c-2f4583813eaf",
                "maxResults": max_results,
                "searchResultPosition": search_result_position,
                # "sortByBoxNumFlag": True
            }
        }
        res = hi_kisapi_proxy_func("/ISAPI/AccessControl/UserInfo/Search?format=json", "POST", orjson.dumps(params)).json()
        if res['UserInfoSearch']['totalMatches'] <= search_result_position or res['UserInfoSearch'][
            'totalMatches'] <= max_results or res['UserInfoSearch']['numOfMatches'] == 0:
            break
        for item in res['UserInfoSearch']['UserInfo']:
            params = {
                "UserInfoAndRightCond": {
                    "employeeNo": item['employeeNo']
                }
            }
        i += 1
    if not employee:
        return response(200, "没有需要删除的人员", {})
    data = {
        "UserInfoDelCond": {
            "EmployeeNoList": employee
        }
    }
    res = hi_kisapi_proxy_func("/ISAPI/AccessControl/UserInfo/Delete?format=json", "PUT", orjson.dumps(data)).json()
    return response(200, "success", employee)


@tool_api.route("/api/tool/appointmentRecords", methods=["POST"])
def visitor_record():
    """访客-查询预约记录"""
    data = request.get_json()
    res = appointment_records(data)
    return response(200, "success", res)


@tool_api.route("/api/tool/visitorSignOutFunc", methods=['POST'])
def visitor_out():
    """访客-签出"""
    data = request.get_json()
    res = visitor_sign_out_func(data)
    return response(200, "success", res)


@tool_api.route("/api/tool/appointmentCancel", methods=['POST'])
def cancel():
    """访客-取消预约"""
    data = request.get_json()
    res = appointment_cancel(data)
    return response(200, "success", res)


@tool_api.route("/api/tool/cabinet_status", methods=['GET'])
def status():
    """更新柜子的状态"""
    res = cabinet_status()
    data = inspect_cabinet_status()
    return response(200, "success", {"r":res, "d":data})


@tool_api.route("/api/tool/cabinet_lock", methods=['GET'])
def cabinet_lock():
    """打开和解锁没有人脸的格口"""
    cabinet_status()
    with g.db_conn.cursor(cursor_factory=extras.RealDictCursor) as cursor:

        query = """
            SELECT 
                id, boxid, "position", "position_id", "row", "column", ip_address
            FROM 
                cabinet
            WHERE 
                space_status != 'empty' OR access_status != 0 OR lock_status != 0 OR exception_status != 0 OR openclose_status != 'close'
        """
        cursor.execute(query)
        result = cursor.fetchall()
        box = []
        for item in result:
            d = {
                "searchID": "ecfef0dd-e604-4266-abae-045d1c14530b",
                "searchResultPosition": 1,
                "maxResults": 5,
                "boxID": item['boxid']
            }
            cabinet_user_info_url = f"http://{item['ip_address']}/ISAPI/IntelligentCabinet/cabinetUserInfo?format=json"
            auth = handle_auth(cabinet_user_info_url)
            s = httpx.post(cabinet_user_info_url, data=orjson.dumps(d), auth=auth).json()

            if s:
                if 'MatchResults' in s:
                    if not s['MatchResults']:
                        q = {
                            "position": str(item['position']),
                            "positionID": int(item['position_id']),
                            "row": int(item["row"]),
                            "column": int(item["column"])
                        }

                        open_space_url = f"http://{item['ip_address']}/ISAPI/IntelligentCabinet/openSpace?format=json"
                        
                        httpx.put(open_space_url, data=orjson.dumps(q), auth=auth)

                        unlock_space_url = f"http://{item['ip_address']}/ISAPI/IntelligentCabinet/unlockSpace?format=json"

                        httpx.put(unlock_space_url, data=orjson.dumps(q), auth=auth)

        return response(0, "success", box)
    

@tool_api.route("/api/tool/cabinet_user_relation", methods=['GET'])
def cabinet_user_relation():
    """
        更新用户绑定的柜子
    """
    with g.db_conn.cursor(cursor_factory=extras.RealDictCursor) as cursor:

        query = """
            SELECT 
                id, boxid, "position", "position_id", "row", "column", ip_address
            FROM 
                cabinet
            WHERE 
                position != 'M'
        """
        cursor.execute(query)
        result = cursor.fetchall()
        box = []
        for item in result:
            d = {
                "searchID": "ecfef0dd-e604-4266-abae-045d1c14530b",
                "searchResultPosition": 1,
                "maxResults": 5,
                "boxID": item['boxid']
            }
            cabinet_user_info_url = "http://192.168.100.119/ISAPI/IntelligentCabinet/cabinetUserInfo?format=json"
            auth = handle_auth(cabinet_user_info_url)
            s = httpx.post(cabinet_user_info_url, data=orjson.dumps(d), auth=auth).json()

            if s:
                if 'MatchResults' in s:
                    if s['MatchResults']:
                        q = """SELECT id FROM cabinet WHERE boxid = %s"""
                        cursor.execute(q, [item['boxid']])
                        cabinet_id = cursor.fetchone()['id']

                        u = """UPDATE persons SET box_id = %s WHERE id_card = %s"""
                        cursor.execute(u, [cabinet_id,s['MatchResults'][0]['employeeNo']])
                        g.db_conn.commit()
                        
                        box.append({s['MatchResults'][0]['employeeNo']: item['boxid']})
                    
        return response(0, "success", {'box': box, 'count': len(box)})


@tool_api.route("/api/tool/delete_room_user", methods=['GET'])
def delete_room_user():
    from loguru import logger
    employees = {
        "2d6dd3e264144faf81158c3d6007875d",
        "23b5dbf4d4194efaa964c1dd5f06c698",
        "dd3c81c66f9340a4bd31d21c31c87190",
        "fb6319ee3fcb45299b041aa9639ef449",
        "9389cc0e482a494788c45171854db3be",
        "4c3f0f18906b4d03b33c7de310bb44ee",
        "d1eef7fef7b9421a80b478f6d4960f56",
        "a057e8e7cfb5459089caaabdca5297ea",
        "0b55f1f1da2c48adbe7bee8be4b0a39c",
        "326e995f1cdc4f718e7f7f474b39b9a0",
        "88370abebad5490da69ae9232ecb4dcc",
        "e02df56941bc4e18a77fd319f44b4aa8",
        "adcae580c7dd4cb181b05ba44311551a",
        "365d06be930f44c2aee5a84d45885215",
        "5837a052f4224702b6b3a37dc7b36d64",
        "c7281a147688496890268de03b93a8e6",
        "5cd59329724248b28048e111af13c3bf",
        "e4c20ad66bb6410b9e290760bcfa3c62",
        "e3c0b452789e4d42ad51f306177e773c",
        "6f07ab549b914ecd906917e05b97dd0b",
        "35a0b6d8d4204e56a4ee4d47ffc4b3ac",
        "8c7feb72ec6f4f8092898094ec0df2c8",
        "49439a68173f4071977ba2a3d670093d",
        "464c45998f47431c9aac13094095129b",
        "eeef268c1f85433d814991fc35ba0c02",
        "c90058aa53c94ec2bba4b1d8c7dea3c5",
        "3d0d487ff6c74ddcb469bcd98456b94e",
        "ba5125ae825f485e88e5acb1f325350b",
        "037fa8aee33843828ca47492d946d1b3",
        "426db02961ec41bb81d0b4fde0cb123e",
        "bb4215797ee84accb13cd26c7f532e41",
        "bf9f440cfb69487e8287ba4cb6ae94bf",
        "37ab41585156438bbaf83c16395c3796",
        "df0503a5748c452ebef8fad2901938bd",
        "9a1429092e8a4ebe8149c40eff8b79fe",
        "88df14c568014c16baa2e3fec2984099",
        "ecc3a4f1343749b19104162f7eebfaea",
        "25a0ba99426d428fa408471d017c76bb",
        "f82c06612f4f41a39f85fed4741e0094",
        "78c320a4659f4046b944cba9bb85b5e2",
        "013329fd759c4bf3b4737fe54915d6ae",
        "4f9928c2a243421195d7b14a28d41495",
        "e646239dcbb444ed874ad707989f51a6",
        "ea578f7876214b13a420ed8e62e9111a",
        "a99d48dd8f3f4a71b73ba76447e45552",
        "f75ecd826f35425dbe6698c215036804",
        "53e9c5beb7344fa4a5c4317c205b0d16",
        "8c8853824ecd47398272aa6fd86a4efb",
        "0768fafacc0c4bbda7b02eef31531e3f",
        "233df37e458148abaa86a23400e93d3d",
        "09f44afae0304d1a86113c0116f9005c",
        "a136ea468bba4d97a54bcfe833fe6db2",
        "f2f933446b074b4c88980ce15f799f71",
        "534242d4ab8d4d49a58e79fc3992cf94",
        "7ad5e3b3526b408eb4cffd4327f3e7b7",
        "a9f884ee7bed4dd0bdb37f9661c331bf",
        "76da486416ec45e2b9ede71ab1dcd444",
        "4c04c67d015c45ad8962c6e73e5ab4ac",
        "4ef819794d464b96b32fab3ba45ed7be",
        "02a4695afaa244c4a051505e506970e8",
        "13287886b77a4d4086734eb3ac01527a",
        "3992295f36404155aa343adffb3db095",
        "ad7223939ddf4960a41d13229f4b26b5",
        "8bb22e9d499d405180533eee06dfce2e",
        "ffb36bfa35f4491f88f5f4a4bbdaa5c9",
        "12deb1e26af3482587ca9d74359bdc78",
        "402d4825806644529ece1dddbe57edf0",
        "c62232d70579403f9c2abfb64f532168",
        "1f5c2df4e7d8466ca52128f8c007d4aa",
        "ba88ae2f7e524acc9db8723e33d53fd1",
        "8827a553a0a64dadb5d74e85fad290ed",
        "4101897814ab40418c70fdd28267db63",
        "96128fcc13de4950b11b10bb60f73542",
        "ab37867a0f6d442ebf78206998354b5b",
        "3462373c4b79438291f722dd8e79c9de",
        "5f8ba4e6ae774247bcf9fd74146e06fd",
        "403d905281d243bd9ba2dbf2ccbb4cde",
        "4998e4d86dfa43788ce268f21474349e",
        "7a709471eee3471585185f9ed835bea8",
        "5810a9502a354ae2b8b5a9e77ea990cd",
        "cfbaf49c54494296bf6b927c5a2d043d",
        "2862a3e75f8c447faa0f51bad20a3cad",
        "2c5e5abfc016481b9cdf1836811d86e5",
        "bd9af6e5675946e4b5a486fd131e4365",
        "de2d1e602a6d43e18afb318cbbd10883",
        "5f98842cd5844f7594b76fc6fb2b23bf",
        "f115a7390b724afda406c4e09d2dd586",
        "0b8b5a4406884280b210bb4579e01b5d",
        "fec4160a5c7a42d5af65730fe7e2b345",
        "25839ed79c594fcca98a45348037f044",
        "80d5427740c34a7aa0d7ea61c5f1fe31",
        "0ba6f5615876409f8e587149267ed52c",
        "2de1f1e11953434f925f94e789310a57",
        "d340cf5f845640408ac0ce65ee640ed1",
        "3ab5e5a7ba5c4cf28459893ae5834575",
    }

    device_code = {
        "AF2823966",
        "AF2823958",
        "AF2823970",
        "AF2823975",
        "AF2823963",
        "AF2823965",
        "AF2823969",
        "AF2823967",
        "AF2823974",
        "AF2823972",
        "AF2823971",
        "AF2823959",
        "AF2823960",
        "AF2823962",
        "AF2823968",
        "AF2823964",
        "AF2823973",
        "AF2823961",
    }   

    logger.add("logs/delete_user_info/file.log", format="{time:YYYY-MM-DD HH:mm:ss} {level} {message}", rotation="00:00", retention="30 days", enqueue=True, filter=lambda record: record["extra"].get("log_type") == "delete_user_info")
    logger.add("logs/delete_face_data_record/file.log", format="{time:YYYY-MM-DD HH:mm:ss} {level} {message}", rotation="00:00", retention="30 days", enqueue=True, filter=lambda record: record["extra"].get("log_type") == "delete_face_data_record")


    for device in device_code:

        for item in employees:
            url = "http://192.168.100.120:9009/isupserver/api/mas/v1/meet/deleteUserInfo"

            params = {
                "deviceIndexCode": device,
                "userInfoDelCond": {
                    "employeeNoList": [
                        {
                            "employeeNo": item,
                        }
                    ],
                    "operateType": "byTerminal",
                }
            }

            resp = httpx.post(url=url, json=params, verify=False).json()

            logger.bind(log_type='delete_user_info').info({"id_card": item, "action": "删除人员信息", "data": resp})


            url2 = "http://192.168.100.120:9009/isupserver/api/mas/v1/meet/deleteFaceDataRecord"
            params2 = {
                "deviceIndexCode": device,
                "bornTime": "1990-01-01",
                "transfer": True,
                "fpid": item,
                "faceLibType": "blackFD",
                "fdid": "1",
                "operateType": "byTerminal",
                "faceType": "normalFace",
            }
            resp2 = httpx.post(url=url2, json=params2, verify=False).json()

            logger.bind(log_type='delete_face_data_record').info({"id_card": item, "action": "删除人脸信息", "data": resp2})

    return response(200, "success", {})


@tool_api.route('/api/tool/room', methods=['POST'])
def room():
    """新增人员信息"""
    data = request.get_json()
    result = handle_room(data.get('room_ids'), data.get('employee_id'), data.get('employee_name'), data.get('qrcode_base64'))
    return response(200, "success", result)

@tool_api.route('/api/tool/delete_room', methods=['POST'])
def delete_room():
    """删除人员信息"""
    data = request.get_json()
    result = signout_handle_room(data.get('room_ids'), data.get('employee_id'), data.get('employee_name'))
    return response(200, "success", result)